﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smart.Data.BaseClasses;
using Smart.Model;
using System.Data;

namespace Smart.Data.Membership
{
    /// <summary>
    /// Implement data logic for User entity
    /// </summary>
    public class UserDL : BaseDataAccess
    {
        private UserDL instance;

        public UserDL(ISmartEntities context)
        {
            Context = context;
        }

        public UserDL GetInstance(ISmartEntities context = null)
        {
            if (instance == null)
            {
                instance = new UserDL(context);
            }
            return instance;
        }

        public List<User> GetUsers()
        {
            return Context.User.ToList<User>();
        }

        public User GetUserByEmail(string email)
        {
            var result = Context.User
                                .Where(u => u.Email.ToLower() == email.ToLower())
                                .FirstOrDefault();

            return result;
        }

        public User SetUser(User user)
        {
            if (user.UserId > 0)
            {
                // Update user
                var updatedUser = Context.User
                                         .Where(u => u.UserId == user.UserId)
                                         .First();

                updatedUser.Email = user.Email;
                updatedUser.Password = user.Password;
                updatedUser.FirstName = user.FirstName;
                updatedUser.LastName = user.LastName;
                updatedUser.Phone = user.Phone;
            }
            else
            {
                // Insert user
                Context.User.AddObject(user);
            }

            if (Context is SmartEntities)
            {
                // Commit all changes
                (Context as SmartEntities).SaveChanges();
            }

            return user;
        }

        public User GetUserById(int userId)
        {
            var result = Context.User
                                .Where(u => u.UserId == userId)
                                .FirstOrDefault();

            return result;
        }
    }
}
